<?php

namespace app\controller;

use app\model\User;
use think\Request;


class Account extends Guest
{

    public function login()
    {
        return view('login');
    }

    public function postLogin(Request $request)
    {
        $email  = $request->post('email');
        $passwd = $request->post('password');
        $user   = User::where('email', $email)->find();
        if (!$user) {
            $this->error('email is not exit');
        }
        if ($user->password != md5($passwd)) {
            $this->error('password is wrong,please try again');
        }
        if ($user->status == 0) {
            $this->error('your account is banned,please contact administrator');
        }
        if ($user->status == -1) {
            $this->error('your account is deleted,sorry');
        }
        $this->setLoginSession($user);
        $this->success('login success', '/');
    }

    private function setLoginSession($user)
    {
        $info = [
            'id'    => $user->id,
            'name'  => $user->first_name . $user->last_name,
            'level' => $user->level
        ];
        session('user', $info);
    }

    public function reg()
    {
        return view('reg');
    }

    public function postReg(Request $request)
    {
        $user             = new User;
        $data             = $request->post();
        $data['password'] = md5($data['password']);
        $uid              = $user->save($data);
        if ($uid === false) {
            $this->error('register error');
        } else {
            $this->setLoginSession($user);
            $this->success('register success', '/');
        }
    }

}
